package com.dxb.sentinel.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * @author DLS
 */
@Service
public class HelloService implements ApplicationContextAware {

    ApplicationContext applicationContext;

    HelloService self;

    public HelloService getSelf() {
        if (self == null) {
            self = applicationContext.getBean(HelloService.class);
        }
        return self;
    }

    /**
     * 限流降级
     *
     * @return
     */
    @SentinelResource(value = "sayHello", blockHandler = "sayHelloExceptionHandler")
    public String sayHello(String name) {
        return "hello," + name;
    }


    /**
     * AOP会失效，无法限流
     *
     * @param name
     * @return {@link String}
     */
    public String test(String name) {
        return getSelf().sayHello(name);
    }

    /**
     * 熔断降级
     *
     * @return
     */
    @SentinelResource(value = "circuitBreaker", fallback = "circuitBreakerFallback", blockHandler = "sayHelloExceptionHandler")
    public String circuitBreaker(String name) {
        if ("zhangsan".equals(name)) {
            return "hello," + name;
        }
        throw new RuntimeException("发生异常");
    }

    public String circuitBreakerFallback(String name) {
        return "服务异常，熔断降级, 请稍后重试!";
    }

    public String sayHelloExceptionHandler(String name, BlockException ex) {
        return "访问过快，限流降级, 请稍后重试!";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
